package com.flca.frw.components
{
	import com.flca.frw.events.EventBroker;
	import com.flca.frw.events.PagingEventGetPage;
	import com.flca.frw.events.PagingEventReady;
	
	import flash.events.MouseEvent;
	
	import mx.containers.HBox;
	import mx.controls.LinkButton;

	public class PagingCtrl extends HBox
	{
		private var _searchId : String;
		private var _currentPagenr : int;
		
		public function PagingCtrl()
		{
			super();
		}
		
		public function setup(aSearchId : String) : void
		{
			_searchId = aSearchId;
			var evname:String = PagingEventReady.getEventName(_searchId);
			EventBroker.instance.addEventListener(evname, handlePagingEvent);
		}
		
		private function handlePagingEvent(ev:PagingEventReady) : void
		{
			var hbox:HBox = view.pagenrs;

			_currentPagenr = ev.pageNr;
			
			hbox.removeAllChildren();
						
			for (var i:int=1; i <= ev.pageCount; i++) {
				hbox.addChild(makePagenr(i, (i==ev.pageNr) ));
			}
			
			view.prev.enabled = ev.pageNr > 1;
			view.next.enabled = ev.pageNr < ev.pageCount;
			
		}
		
		private function makePagenr(nr:int, currentPage:Boolean) : LinkButton
		{
			var r:LinkButton = new LinkButton();
			
			r.label = "" + nr;
			if (currentPage) {
				r.setStyle("color", "red");
			}
			r.addEventListener(MouseEvent.CLICK, handlePagenrClicked);
			
			return r;
		}
		
		private function handlePagenrClicked(event:MouseEvent) : void
		{
			var lb:LinkButton = event.currentTarget as LinkButton;
			
			var nr:int = Number(lb.label) - 1;
			sendRequest(nr);
		}
		
		private function sendRequest(nr:int) : void
		{
			EventBroker.instance.sendEvent(new PagingEventGetPage(_searchId, nr));
		}		

		protected function getPrevPage() : void 
		{
			sendRequest(_currentPagenr-2);
		}

		protected function getNextPage() : void 
		{
			sendRequest(_currentPagenr);
		}
		
		private function get view() : PagingView {
			return this as PagingView;
		}
	}
}